package com.eduagent.xwqeduagent.tools.studenttools;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.eduagent.xwqeduagent.config.ToolResultHolder;
import com.eduagent.xwqeduagent.constant.Constant;
import com.eduagent.xwqeduagent.openFeign.client.GetInfoClient;
import com.eduagent.xwqeduagent.openFeign.entity.Course;
import com.eduagent.xwqeduagent.openFeign.result.Result;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class CourseTools {

    @Autowired
    private GetInfoClient getInfoClient;

    private static final String FIELD_NAME_FORMAT = "{}_{}";  // 提取格式字符串常量

    /**
     * 根据课程id查询课程信息
     *
     * @param courseId 课程id
     * @return 课程信息
     */
    @Tool(description = "根据课程ID查询课程详细信息")
    public Course queryCourseById(@ToolParam(description = "课程ID") String courseId, ToolContext toolContext) {
        return Optional.ofNullable(courseId)
                .map(id -> {
                    Result<Course> result = getInfoClient.getCourseById(id);
                    return result.getData();
                })
                .map(course -> {
                    // 存储数据的字段名
                    String field = StrUtil.format(FIELD_NAME_FORMAT,
                            StrUtil.lowerFirst(Course.class.getSimpleName()),
                            course.getId());
                    // 存储的key
                    var requestId = Convert.toStr(toolContext.getContext().get(Constant.REQUEST_ID));
                    ToolResultHolder.put(requestId, field, course);
                    return course;
                })
                .orElse(null);
    }
}
